package com.uenpay.oem.ui.verifyinput;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.oem.R;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.ui.reserver.RechargeActivity;
import com.uenpay.oem.ui.withdraw.WithdrawActivity;
import com.uenpay.oem.widget.view.InputView;
import com.uenpay.util.app.ActivityStack;
import com.uenpay.util.common.DensityUtils;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xyz.royliu.library.AKeyboardManager;

/**
 * Author: liulou
 * Date: 2017/6/27.
 * desc: 验证信息输入页面（如验证码，支付密码等）
 */

public class VerifyInputActivity extends AppCompatActivity {

    private int MARGIN_KEYBOARD_HEIGHT = DensityUtils.dip2px(30);

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_close)
    ImageButton ibtnClose;
    @BindView(R.id.tv_subtitle)
    TextView tvSubtitle;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.tv_send_retry)
    TextView tvSendRetry;
    @BindView(R.id.rl_send_retry)
    RelativeLayout rlSendRetry;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.inputview)
    InputView inputView;
    @BindView(R.id.root_content)
    LinearLayout llRootContent;

    private String mTitle; //主标题
    private String mSubTitle; //副标题
    private String mAmount; //金额
    private String mOtherDesc; //金额下面的说明，如扣除费率
    private boolean isShowSendRetry; //是否显示重新发送验证码
    private boolean isShowForget; //是否显示忘记密码
    private boolean isShowPwd; //是否使用圆点隐藏密码
    private int mInputLength; //输入密码/验证码长度


    private AKeyboardManager mKeyBoardManager;

    //倒计时器
    private int leftTime = 60;
    private boolean isCounting = false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            leftTime--;
            isCounting = true;
            if (leftTime >= 0) {
                mHandler.sendEmptyMessageDelayed(0, 1000);
                tvSendRetry.setText(leftTime + "s");
                tvSendRetry.setClickable(false);
                tvSendRetry.setEnabled(false);
                return;
            }
            //重置时间
            leftTime = 60;
            isCounting = false;
            tvSendRetry.setText("重新获取");
            tvSendRetry.setClickable(true);
            tvSendRetry.setEnabled(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_input);
        ButterKnife.bind(this);
        ActivityStack.getInstance().push(this);
        mKeyBoardManager = new AKeyboardManager(this);
        mKeyBoardManager.attachTo(inputView, AKeyboardManager.KEYBOARD_TYPE_NUM);

        initDefaultView();
    }

    private void initDefaultView() {
        if (getIntent() == null) return;
        mTitle = getIntent().getStringExtra("title");
        mSubTitle = getIntent().getStringExtra("subtitle");
        mAmount = getIntent().getStringExtra("amount");
        mOtherDesc = getIntent().getStringExtra("desc");
        isShowSendRetry = getIntent().getBooleanExtra("show_send_retry", false);
        isShowForget = getIntent().getBooleanExtra("forget_pwd", false);
        isShowPwd = getIntent().getBooleanExtra("show_pwd", false);
        mInputLength = getIntent().getIntExtra("input_length", 6);

        if (!TextUtils.isEmpty(mTitle)) tvTitle.setText(mTitle);
        if (!TextUtils.isEmpty(mSubTitle)) {
            tvSubtitle.setText(mSubTitle);
            tvSubtitle.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(mAmount)) {
            tvAmount.setText("¥ " + mAmount);
            tvAmount.getPaint().setFakeBoldText(true);
        }
        if (!TextUtils.isEmpty(mOtherDesc)) {
            tvDesc.setText(mOtherDesc);
            tvDesc.setVisibility(View.VISIBLE);
        }
        rlSendRetry.setVisibility(isShowSendRetry ? View.VISIBLE : View.GONE);
        //如果需要显示重新发送，做倒计时
        if (isShowSendRetry) {
            leftTime = 60;
            mHandler.sendEmptyMessage(0);//开启倒计时
        }

        tvForget.setVisibility(isShowForget ? View.VISIBLE : View.GONE);
        inputView.setShowPwd(isShowPwd);
        inputView.setPasswordLength(mInputLength);
        inputView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mInputLength)});

        inputView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == inputView.getPasswordLength()) {
                    Intent i = new Intent();
                    Bundle b = new Bundle();
                    b.putString("pwd", s.toString());
                    i.putExtras(b);
                    setResult(RESULT_OK, i);
                    finish();
                }
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(DensityUtils.dip2px(20), 0, DensityUtils.dip2px(20), mKeyBoardManager.getKeyBoardHeight() + MARGIN_KEYBOARD_HEIGHT);
            lp.gravity = Gravity.BOTTOM;
            llRootContent.setLayoutParams(lp);
        }
    }

    @OnClick({R.id.ibtn_close, R.id.tv_send_retry, R.id.tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_close:
                finish();
                break;
            case R.id.tv_send_retry:
                leftTime = 60;
                mHandler.sendEmptyMessage(0);//开启倒计时
                RxBus.$().post(RechargeActivity.TAG, new CommonEvent(RxBusEventConstant.EVENT_RETRY_SEND_CODE));
                break;
            case R.id.tv_forget:
                Intent intent = new Intent(VerifyInputActivity.this, SetPayPwdActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStack.getInstance().remove(this);
    }
}
